<template>
  <el-dialog
    v-model="visibility"
    :title="props.rowData.id ? config.button.text.edit : config.button.text.add"
    append-to-body
    draggable
    :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="config.form.label.width"
      status-icon>
      <el-row>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="名称"
            prop="name">
            <el-input
              v-model="formData.name"
              placeholder="名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="启用状态"
            prop="isEnable">
            <el-select
              v-model="formData.isEnable"
              placeholder="选择"
              clearable>
              <el-option
                :label="config.button.text.enable"
                :value="true" />
              <el-option
                :label="config.button.text.stop"
                :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
        <el-button
          type="primary"
          @click="saveEvent">
          {{ config.button.text.save }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import config from "@/common/element-plus/config";
import ApiSysRole from "@/api/modules/sys-role"
import { useValidator } from "@/hooks/useValidator";

const visibility = ref(false)
const formData = ref({})
const formRef = ref()
const { required, validate, clearValidate } = useValidator()

const formRules = {
  name: [required("名称")],
  isEnable: [required("状态", "change")],
}

const props = defineProps(["rowData"])

const emits = defineEmits(["save"])

watch(() => visibility.value, (newVal) => {
  if (newVal) {
    if (!props.rowData.id) {
      formData.value = {
        ...props.rowData,
        isEnable: true,
      };
    } else {
      formData.value = { ...props.rowData };
    }
    setTimeout(() => {
      clearValidate(formRef.value)
    })
  }
}, { immediate: true })

const saveEvent = async () => {
  await validate(formRef.value)
  if (formData.value.id) {
    await ApiSysRole.update(formData.value)
  } else {
    await ApiSysRole.insert(formData.value)
  }
  emits("save")
}

defineExpose({ visibility })
</script>

<style lang="scss" scoped>
@media screen and (max-width: 700px) {
  :deep(.el-form-item__label) {
    width: 80px !important;
  }
}
</style>
